package com.kun.kunkunmall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.kun.kunkunmall.order.config.AlipayConfig;
import com.kun.kunkunmall.order.service.OrderService;
import com.kun.kunkunmall.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

@RestController
public class OrderPayedListener {


    @Autowired
    private OrderService orderService;

    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo vo,HttpServletRequest request) throws AlipayApiException {
        // 只要我们收到了支付宝的订单支付成功的异步通知，并且返回success，支付宝就停止通知了
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        Set<String> keys = parameterMap.keySet();
//        for (String key : keys) {
//            String parameter = request.getParameter(key);
//            System.out.println("参数名字"+key+"参数值"+parameter);
//        }
//        System.out.println("收到支付宝的异步通知，数据是："+parameterMap);

        // 根据支付宝传递过来的支付结果去修改订单状态
        // 修改订单状态之前，有一个核心的操作就是验签
        String[] temp = request.getQueryString().split("&");
        LinkedHashMap<String, String> map =  new LinkedHashMap<String, String>();
        //把拆分数据放在map集合内
        for (int i = 0; i < temp.length; i++) {
            String[] arr = temp[i].split("=", 2); //通过"="号分割成2个数据
            String[] tempAagin = new String[arr.length]; //再开辟一个数组用来接收分割后的数据
            for (int j = 0; j < arr.length; j++) {
                tempAagin[j] = arr[j];
            }
            map.put(tempAagin[0], tempAagin[1]);
        }
        System.out.println(map);
        //验签方法
        boolean signVerified = AlipaySignature.rsaCheckV1(map, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.CHARSET,AlipayConfig.SIGNTYPE);
        if (signVerified){
            // 签名验证成功，说明这个是支付宝传递过来的数据
            System.out.println("签名验证成功");
            return orderService.handlePayResult(vo);
        }else {
            // 签名验证失败
            System.out.println("签名验证失败");
            return "error";
        }
    }
}
